<template>
  <view style="width: 100%; height: 100%">
    <l-echart ref="chartRef"></l-echart>
  </view>
</template>

<script lang="ts" setup name="th-echarts">
import * as echarts from 'echarts';

const props = defineProps({
  option: {
    type: Object,
    default: () => {
      return {};
    },
  },
});

let myChart = null;
const chartRef = ref(null);
onMounted(() => {
  // 组件能被调用必须是组件的节点已经被渲染到页面上
  setTimeout(async () => {
    // console.log('onMounted-chartRef', chartRef.value);
    if (!chartRef.value) return;
    myChart = await chartRef.value.init(echarts);
    // myChart.setOption(option)
    // console.log('onMounted-myChart', myChart);
  }, 300);
});

const initChart = () => {
  setTimeout(async () => {
    // console.log('initChart', props.option);
    myChart.setOption(props.option);
    // console.log(myChart, props.option);
  }, 300);
};

watch(
  () => props.option,
  (val) => {
    // console.log('watch', val);
    if (val) {
      initChart();
    }
  },
  {
    immediate: true,
    deep: true,
  },
);

const getResize = () => {
  setTimeout(async () => {
    console.log('chartRef.value', chartRef.value); // 注释后下方代码可能会报错
    chartRef.value.resize();
    setTimeout(async () => {
      initChart();
    }, 300);
  }, 300);
};

defineExpose({
  getResize,
});
</script>
